<template>
    <div class="scTable" :style="{ height: _height }" ref="scTableMain" v-loading="loading">
      <div class="scTable-table" :style="{ height: _table_height }">
        <el-table
          v-bind="$attrs"
          :data="tableData"
          :row-key="rowKey"
          :key="toggleIndex"
          ref="scTable"
          :height="height === 'auto' ? null : '100%'"
          :size="size"
          :border="border"
          :stripe="stripe"
          :summary-method="remoteSummary ? remoteSummaryMethod : summaryMethod"
          @sort-change="sortChange"
          @filter-change="filterChange"
        >
          <template v-for="(item, index) in userColumn" :key="index">

            <el-table-column
              v-if="!item.hide"
              :column-key="item.prop"
              :label="item.label"
              :prop="item.prop"
              :width="item.width"
              :sortable="item.sortable"
              :fixed="item.fixed"
              :filters="item.filters"
              :filter-method="remoteFilter || !item.filters ? null : filterHandler"
              :show-overflow-tooltip="item.showOverflowTooltip"
            >
              <template #default="scope">
                <slot :name="item.prop" v-bind="scope">
                  {{ scope.row[item.prop] }}
                </slot>
              </template>
            </el-table-column>
          </template>
          <el-table-column min-width="1"></el-table-column>
          <template #empty>
            <el-empty :description="emptyText" :image-size="100"></el-empty>
          </template>
        </el-table>
      </div>
      <div class="scTable-page" v-if="!hidePagination || !hideDo">
        <div class="scTable-pagination">
          <el-pagination
            v-if="!hidePagination"
            background
            :small="true"
            :layout="paginationLayout"
            :total="total"
            :page-size="scPageSize"
            :page-sizes="pageSizes"
            v-model:currentPage="currentPage"
            @current-change="paginationChange"
            @update:page-size="pageSizeChange"
          ></el-pagination>
        </div>
        <div class="scTable-do" v-if="!hideDo">
          <el-button v-if="!hideRefresh" @click="refresh" :icon="Refresh" circle style="margin-left: 15px"></el-button>
          <el-popover
            v-if="column"
            placement="top"
            title="列设置"
            :width="500"
            trigger="click"
            :hide-after="0"
            @show="customColumnShow = true"
            @after-leave="customColumnShow = false"
          >
            <template #reference>
              <el-button :icon="SetUp" circle style="margin-left: 15px"></el-button>
            </template>
            <columnSetting
              v-if="customColumnShow"
              ref="columnSetting"
              @userChange="columnSettingChange"
              @save="columnSave"
              @back="columnSettingBack"
              :column="userColumn"
            ></columnSetting>
          </el-popover>
          <el-popover v-if="!hideSetting" placement="top" title="表格设置" :width="400" trigger="click" :hide-after="0">
            <template #reference>
              <el-button :icon="Setting" circle style="margin-left: 15px"></el-button>
            </template>
            <el-form label-width="80px" label-position="left">
              <el-form-item label="表格尺寸">
                <el-radio-group  :size="size" @change="configSizeChange">
                  <el-radio-button label="large">大</el-radio-button>
                  <el-radio-button label="default">正常</el-radio-button>
                  <el-radio-button label="small">小</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="样式">
                <el-checkbox :border="border" label="纵向边框"></el-checkbox>
                <el-checkbox :stripe="stripe" label="斑马纹"></el-checkbox>
              </el-form-item>
            </el-form>
          </el-popover>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
import {
    Setting,SetUp,Refresh 
} from '@element-plus/icons-vue'
  import { ref, reactive, watch, computed, onMounted } from 'vue';
  import {columnSettingGet, parseData, settings,columnSettingSave} from "@/config/table";
  const config = settings()
  const props = defineProps({
    tableName: { type: String, default: "" },
    apiObj: { type: Object, default: () => ({}) },
    params: { type: Object, default: () => ({}) },
    data: { type: Array, default: () => ([]) },
    height: { type: [String, Number], default: "100%" },
    size: { type: String, default: "default" },
    border: { type: Boolean, default: false },
    stripe: { type: Boolean, default: false },
    pageSize: { type: Number, default: 20 },
    pageSizes: { type: Array, default: [10, 20, 30, 40, 50] },
    rowKey: { type: String, default: "" },
    summaryMethod: { type: Function, default: null },
    column: { type: Array, default: () => ([]) },
    remoteSort: { type: Boolean, default: false },
    remoteFilter: { type: Boolean, default: false },
    remoteSummary: { type: Boolean, default: false },
    hidePagination: { type: Boolean, default: false },
    hideDo: { type: Boolean, default: false },
    hideRefresh: { type: Boolean, default: false },
    hideSetting: { type: Boolean, default: false },
    paginationLayout: { type: String, default:  "total, sizes, prev, pager, next, jumper" },
  });
  
  const emits = defineEmits(['dataChange']);
  
  const scPageSize = ref(props.pageSize);
  const isActivat = ref(true);
  const emptyText = ref("暂无数据");
  const toggleIndex = ref(0);
  const tableData = ref<any>([]);
  const total = ref(0);
  const currentPage = ref(1);
  const prop = ref(null);
  const order = ref('desc');
  const loading = ref(false);
  const tableParams = ref(props.params);
  const userColumn = ref<any>([]);
  const customColumnShow = ref(false);
  const summary = ref({});
  const _height = computed(() => (Number(props.height) ? `${Number(props.height)}px` : props.height));
  const _table_height = computed(() => (props.hidePagination && props.hideDo ? "100%" : "calc(100% - 50px)"));
  
  watch(() => props.data, (newData) => {
    tableData.value = newData;
    total.value = tableData.value.length;
  });
  
  watch(() => props.apiObj, () => {
    tableParams.value = props.params;
    refresh();
  });
  
  watch(() => props.column, (newColumn) => {
    console.log(newColumn);
    
    userColumn.value = newColumn;
  });
  
  onMounted(async () => {
    if (props.column) {
      await getCustomColumn();
    } else {
      userColumn.value = props.column;
    }
  
    if (props.apiObj) {
      await getData();
    } else if (props.data) {
      tableData.value = props.data;
      total.value = tableData.value.length;
    }
  });
  
  async function getCustomColumn() {
    userColumn.value = await columnSettingGet(props.tableName, props.column);
  }
  
  async function getData() {
    loading.value = true;
    const reqData = {
      [config.request.page]: currentPage.value,
      [config.request.pageSize]: scPageSize.value,
      [config.request.prop]: prop.value,
      [config.request.order]: order.value,
    };
  
    if (props.hidePagination) {
      delete reqData[config.request.page];
      delete reqData[config.request.pageSize];
    }
  
    Object.assign(reqData, tableParams.value);
  
    try {
      const res = await props.apiObj.get(reqData);
      const response = parseData(res);
      if (response.code !== config.successCode) {
        emptyText.value = response.msg;
      } else {
        emptyText.value = "暂无数据";
        tableData.value = props.hidePagination ? response.data : response.rows;
        total.value = response.total;
        summary.value = response.summary;
      }
      emits('dataChange', res, tableData.value);

    } catch (error) {
      //emptyText.value = error.statusText || "数据格式错误";
    } finally {
      loading.value = false;
    }
  
  }
  
  function paginationChange() {
    getData();
  }
  
  function pageSizeChange(size: number) {
    scPageSize.value = size;
    getData();
  }
  
  function refresh() {
    clearSelection();
    getData();
  }
  
  function upData(params: any, page = 1) {
    currentPage.value = page;
    clearSelection();
    Object.assign(tableParams.value, params);
    getData();
  }
  
  function reload(params: any, page = 1) {
    currentPage.value = page;
    tableParams.value = params;
    clearSelection();
    clearSort();
    clearFilter();
    getData();
  }
  
  function clearSort() {
    // const el = scTable.value;
    // el.clearSort();
    // prop.value = null;
    // order.value = null;
  }
  
  function clearFilter() {
    // const el = scTable.value;
    // el.clearFilter();
  }
  
  function clearSelection() {
    // const el = scTable.value;
    // el.clearSelection();
  }
  
  function sortChange(sort: any) {
    if (sort.prop) {
      prop.value = sort.prop;
      order.value = sort.order === 'descending' ? 'desc' : 'asc';
    } else {
      prop.value = null;
      order.value = 'descending';
    }
  
    if (props.remoteSort) {
      getData();
    }
  }
  
  function filterChange(filters: any) {
    const filterObj: Record<string, any> = {};
    Object.keys(filters).forEach(key => {
      filterObj[key] = filters[key].length > 0 ? filters[key] : null;
    });
    Object.assign(tableParams.value, filterObj);
  
    if (props.remoteFilter) {
      getData();
    }
  }
  
  function filterHandler(value: any, row: any, column: any) {
    const property = column['property'];
    return row[property] === value;
  }
  
  function remoteSummaryMethod(param: any) {
    return summary.value;
  }
  
  function columnSettingChange(value: any) {
    userColumn.value = value;
  }
  
  function columnSave(value: any) {
    userColumn.value = value;
    columnSettingSave(props.tableName, value);
    customColumnShow.value = false;
    toggleIndex.value += 1;
  }
  
  function columnSettingBack() {
    customColumnShow.value = false;
  }
  
  function configSizeChange(value: any) {
    toggleIndex.value += 1;
  }
  
  watch(currentPage, () => {
    if (isActivat.value) {
      getData();
    }
  });
  
  </script>
  <style scoped>
  .scTable {}
  .scTable-table {height: calc(100% - 50px);}
  .scTable-page {height:50px;display: flex;align-items: center;justify-content: space-between;padding:0 15px;}
  .scTable-do {white-space: nowrap;}
  .scTable:deep(.el-table__footer) .cell {font-weight: bold;}
  .scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-horizontal {height: 12px;border-radius: 12px;}
  .scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-vertical {width: 12px;border-radius: 12px;}
</style>